﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using System.Xml.Serialization;
using MyAnimeList.Model;

namespace MyAnimeList
{
    public partial class FrmMainForm : Form
    {
        public bool LoggedIn { private get; set; }
        public string LoaiDanhSach { private get; set; }
        public string TaiKhoan { private get; set; }
        public string MatKhau { private get; set; }
        private MyanimelistModel result { get; set; }

        private bool firstLoad = true;
        public FrmMainForm()
        {
            InitializeComponent();
            var username = ConfigurationManager.AppSettings["UserName"];
            var password = ConfigurationManager.AppSettings["Password"];

            if (username != null && password != null)
            {
                var message = LibDataProcess.Login(username, password);
                if (message != null)
                {
                    LoggedIn = false;
                    MessageBox.Show(message, "Error", MessageBoxButtons.OK);
                }
                else
                {
                    LoggedIn = true;
                }
            }
        }

        private async void frmMainForm_Load(object sender, EventArgs e)
        {
            if (LoggedIn)
            {
                progressBar1.MarqueeAnimationSpeed = 30;
                progressBar1.Style = ProgressBarStyle.Marquee;

                LoaiDanhSach = "anime";
                TaiKhoan = ConfigurationManager.AppSettings["UserName"];
                MatKhau = ConfigurationManager.AppSettings["Password"];
                lblTrangThai.Text = "Loading anime list";
                
                var url = ConfigurationManager.AppSettings["ApiList"] ?? "https://myanimelist.net/malappinfo.php";
                url += string.Format("?status=all&type={0}&u={1}", LoaiDanhSach, TaiKhoan);
                var uri = new Uri(url);
                using (var client = new WebClient())
                {
                    var xml = await client.DownloadStringTaskAsync(uri);

                    var ser = new XmlSerializer(typeof(MyanimelistModel));
                    result = ser.Deserialize(new StringReader(xml)) as MyanimelistModel;

                    if (result != null)
                    {
                        FillTableTab(1, grvOnGoing);
                    }

                    progressBar1.MarqueeAnimationSpeed = 0;
                    progressBar1.Visible = false;
                    lblTrangThai.Text = "Done";
                }
            }
            else
            {
                var frmLogIn = new FrmLogIn();
                frmLogIn.Show();
            }
        }

        private void FillTableTab(int status, DataGridView target)
        {

            var source = new List<object>();
            foreach (var o in result.Anime.FindAll(o => o.My_status == status).OrderBy(o => o.Series_title))
            {
                var start = DateTime.Today;
                var end = DateTime.Today;

                dynamic item = new
                {
                    AnimeTitle = o.Series_title,
                    Score = o.My_score,
                    Type = o.Series_type,
                    Progress = o.My_watched_episodes,
                    Synonyms = o.Series_synonyms,
                    StartedDate = o.My_start_date,
                    FinishedDate = o.My_finish_date,
                    Days = DateTime.TryParse(o.My_start_date, out start) && DateTime.TryParse(o.My_finish_date, out end) ? 
                        (end - start).Days.ToString() : string.Empty
                
            };

               


                source.Add(item);
            }

            target.DataSource = source;
        }

        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var frmLogIn = new FrmLogIn();
            frmLogIn.Show();
        }

        private void tabOnGoing_Enter(object sender, EventArgs e)
        {
            if (firstLoad == false)
            {
                FillTableTab(1, grvOnGoing);
            }
        }

        private void tabOnGoing_Leave(object sender, EventArgs e)
        {
            firstLoad = false;
        }

        private void tabPage2_Enter(object sender, EventArgs e)
        {
            FillTableTab(2, grvCompleted);
        }

        private void tabPlan_Enter(object sender, EventArgs e)
        {
            FillTableTab(6, grvPlan);
        }
    }
}